const { logger } = require("../config/logConfig")

const Course = require("../models/Course")
const utils = require('../config/utils')
// 课程列表
async function courseList (req, res) {
  let condition = utils.completeSelect(req.body)
  let pageObj = utils.pageSelect(req.body)
  try {
    const course = await Course.findAndCountAll({
      offset: pageObj.skip,
      limit: pageObj.limit,
      where: condition,
      order: [['createdAt', 'DESC']], // 根据创建时间倒序排序
      distinct: true,
      attributes: {
        exclude: ["createdAt", "updatedAt"],
      },
    })
    if (!course) {
      utils.responseContent(res, 'OK', 200, data = { list: [], total: 0, pageSize: 10, pageNum: 1 })
    }
    utils.responseContent(res, 'OK', 200, data = {
      list: course.rows,
      pageNum: (pageObj.skip / pageObj.limit) + 1,
      pageSize: pageObj.limit,
      total: course.count
    })
  } catch (error) {
    logger.error(JSON.stringify(error))
    res.status(500).json({ msg: '获取课程表表失败', code: 400 })
  }
}
/**
 * 新增
 * @param {*} req
 * @param {*} res 
 */
async function courseAdd (req, res) {
  for (const attr in req.body) {
    if (attr === 'type' && req.body[attr].length === 0) {
      return res.status(200).json({ msg: `课程类型不能为空`, code: 40015 })
    } else {
      if (req.body[attr] === '') {
        return res.status(200).json({ msg: `${ Course.tableAttributes[attr].comment }(${ attr })不能为空`, code: 40015 })
      }
    }
  }
  const { name, code, type, class_time, dur_class_time, content, address, stats } = req.body
  try {
    const count = await Course.count()
    let id
    if (count === 0) {
      // 如果是首次创建 则使用随机生成的 ID
      const randomNum = Math.floor(Math.random() * 1000000).toString().padStart(6, '0')
      id = `801${ randomNum }`
    } else {
      // 获取第一条数据的ID，并在此基础上递增生成后续数据的 ID
      const maxIdCourse = await Course.findOne({ order: [['id', 'DESC']] })
      const maxId = parseInt(maxIdCourse.id) // 获取最大ID的数值部分
      id = maxId + 1
    }
    // 创建课程
    await Course.create({ id, name, code, type, class_time, dur_class_time, content, address, stats })
    res.status(200).json({ msg: 'OK', code: 0 })
  } catch (error) {
    logger.error(JSON.stringify(error))
    res.status(200).json({ msg: '新增课程表失败', code: 400 })
  }
}
/**
 * 详情
 * @param {*} req 
 * @param {*} res 
 */
async function courseDetail (req, res) {
  const { id } = req.query
  try {
    const course = await Course.findOne({ where: { id } })
    if (course === null) {
      res.status(200).json({ msg: '查询课程信息失败', code: 0 })
    } else {
      res.status(200).json({ msg: 'OK', code: 0, data: { data: course } })
    }
  } catch (error) {
    res.status(200).json({ msg: error, code: 0 })
  }
}
// 更新用户
async function courseUpd (req, res) {
  for (const attr in req.body) {
    if (attr === 'type' && req.body[attr].length === 0) {
      return res.status(200).json({ msg: `课程类型不能为空`, code: 40015 })
    } else {
      if (req.body[attr] === '') {
        return res.status(200).json({ msg: `${ Course.tableAttributes[attr].comment }(${ attr })不能为空`, code: 40015 })
      }
    }
  }
  const { id, name, code, type, class_time, dur_class_time, content, address, stats } = req.body
  try {
    const course = await Course.findOne({ where: { id } })
    if (course === null) {
      res.status(200).json({ msg: '查询用户失败', code: 0 })
    } else {
      let mtime = new Date().getTime()
      await Course.update({ name, code, type, stats, class_time, mtime, dur_class_time, address, content }, {
        where: {
          id,
        }
      })
    }
    res.status(200).json({ msg: 'OK', code: 0 })
  } catch (error) {
    res.status(200).json({ msg: error, code: 200 })
  }
}
async function delCourse (req, res) {
  let { id } = req.body
  try {
    if (id === '') {
      res.stats(200).json({msg: 'ID为空!', code: 0})
    }
    await Course.destroy({ where: { id } })
    res.stats(200).json({msg: '删除成功', code: 0})
  } catch (error) {
    res.status(200).json({ msg: error, code: 200 })
  }
}
module.exports = { courseAdd, courseList, courseDetail, courseUpd, delCourse }